package com.iflytek.http.impl;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.iflytek.httpoperation.SpApp;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;


public class HttpOperationService extends Service
{
	protected int NEVER_SHUT_DOWN = -1;
	private SpApp mApplication;
	private Handler mHandler = new Handler();
	private ExecutorService httpExecutor;
	private int taskCounter = 0;
	private int idleTime = 30;
	private boolean stopAfterDone = false;

	private Runnable stopServiceRun = new Runnable()
	{
		public void run() {
			HttpOperationService.this.stopSelf();
		}
	};

	void doRequest(AbstractOperation operation)
	{
		if (this.httpExecutor == null)
			this.httpExecutor = Executors.newCachedThreadPool();
		this.mHandler.removeCallbacks(this.stopServiceRun);
		operation.setServiceAndHandler(this, this.mApplication.getHttpOp().mHandler);
		this.httpExecutor.execute(operation);
	}

	void stopAfterDone() {
		if (getCounter() <= 0) {
			mHandler.post(this.stopServiceRun);
		}
		stopAfterDone = true;
	}

	void stopServicNow() {
		stopSelf();
	}

	public void onCreate()
	{
		super.onCreate();
		this.mApplication = (SpApp)getApplication();
		this.mApplication.getHttpOp().onServiceStarted(this);
	}

	public void onDestroy()
	{
		super.onDestroy();
		this.httpExecutor.shutdownNow();
		System.out.println("shutting down");
	}

	public IBinder onBind(Intent intent)
	{
		return null;
	}

	public int onStartCommand(Intent intent, int flags, int startId)
	{
		return super.onStartCommand(intent, 2, startId);
	}

	protected void setIdleInMinute(int idleTime)
	{
		if (idleTime < -1) {
			throw new IllegalArgumentException("must be bigger than -1");
		}
		this.idleTime = idleTime;
	}

	synchronized void increaseCounter()
	{
		this.taskCounter += 1;
	}

	synchronized void decreaseCounter() {
		this.taskCounter -= 1;
		System.out.println("couter:" + this.taskCounter);
		if (this.taskCounter <= 0) {
			if (this.stopAfterDone) {
				stopSelf();
				return;
			}

			if (this.idleTime != -1)
				this.mHandler.postDelayed(this.stopServiceRun, this.idleTime * 60 * 1000);
		}
	}

	synchronized int getCounter(){
		return this.taskCounter;
	}
}